package com.itheima.web;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * @author: libin
 * @date: 2019/11/29 10:51
 * @version: 1.0
 * @describe:
 */
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private RedisUtils redisUtils;
    @Reference
    private MemberService memberService;
    /**
     * 用户快速登陆
     * @param map
     * @return
     */
    @RequestMapping("/check")
    public Result check(@RequestBody Map map, HttpServletRequest request) {
        //获取传过来的telephone和validateCode数据
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");

        //1.验证码对比
        String redisCode = redisUtils.get(telephone+ RedisMessageConstant.SENDTYPE_LOGIN);
        if (null == redisCode || !redisCode.equals(validateCode)) {
            return new Result(false,"验证码错误");
        }

        //2.看看是不是我们的会员
        Member member= memberService.findBytelephone(telephone);

        //3.不是就自动注册会员
        if (member == null) {
            member=new Member();//初始化
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            member=memberService.add(member);//获取会员id
        }

        //4.把信息放入session
        request.getSession().setAttribute("member",member);

        return new Result(true, MessageConstant.LOGIN_SUCCESS);

    }
}
